package com.xiaoKe.zhonghzu.global.base;

/**
 * @ProjectName : xiaoke-pad-zhongzhu
 * @Author : Shijingna
 * @Time : 2024/8/1 13:35
 * @Description : 文件描述
 */
import android.content.Context;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;

public class EqualWidthLayoutManager extends RecyclerView.LayoutManager {

    private int totalWidth = 0;
    private int totalHeight = 0;
    private int itemWidth = 0;
    private int itemHeight = 0;
    private int spacing = 0;

    public EqualWidthLayoutManager(Context context) {
        super();
    }
    public EqualWidthLayoutManager(Context context, int spacing,boolean ab) {
        super();
    }
    @Override
    public void onLayoutChildren(@NonNull RecyclerView.Recycler recycler, @NonNull RecyclerView.State state) {
        super.onLayoutChildren(recycler, state);

        // Clear previous layout
        detachAndScrapAttachedViews(recycler);

        if (getItemCount() == 0) return;

        // Calculate width of each item
        int width = getWidth();
        int count = getItemCount();
        int itemCount = count > 0 ? count : 1;

        itemWidth = (width - getPaddingLeft() - getPaddingRight()) / itemCount;
        itemHeight = getHeight() - getPaddingTop() - getPaddingBottom();
        spacing = (width - itemWidth * count) / (count + 1);

        int leftOffset = getPaddingLeft() + spacing;
        int topOffset = getPaddingTop();

        for (int i = 0; i < count; i++) {
            View view = recycler.getViewForPosition(i);
            addView(view);
            measureChildWithMargins(view, 0, 0);
            layoutDecorated(view, leftOffset, topOffset, leftOffset + itemWidth, topOffset + itemHeight);
            leftOffset += itemWidth + spacing;
        }
    }

    @Override
    public RecyclerView.LayoutParams generateDefaultLayoutParams() {
        return new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
    }
}
